﻿using System;
using System.Web;

namespace DflyingForum.Core.Framework
{
    /// <summary>
    /// Cookie操作类
    /// </summary>
    public class DflyingCookie
    {
        /// <summary>
        /// 获取指定Key的Cookie值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookieValue(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
            string str = string.Empty;
            if (cookie != null)
            {
                str = cookie.Value;
            }
            return str;
        }

        /// <summary>
        /// 清除指定key的Cookie
        /// </summary>
        /// <param name="key"></param>
        public static void ClearCookie(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie != null)
            {
                //过期这么指定的哈
                cookie.Expires = DateTime.Now.AddYears(-3);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 添加一个cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCookie(string key, string value)
        {
            HttpCookie cookie = new HttpCookie(key, value);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 添加一个cookie,指定过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expires">过期时间</param>
        public static void SetCookie(string key, string value, DateTime expires)
        {
            HttpCookie cookie = new HttpCookie(key)
            {
                Value = value,
                Expires = expires
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
